//
//  Tool.swift
//  ZYChat
//
//  Created by admin on 2019/10/31.
//  Copyright © 2019 admin. All rights reserved.
//

import UIKit
import Foundation
//MARK: - UserDefaults
public var userDefaults: UserDefaults = {
    print("----UserDefaults.standard----")
    return UserDefaults.standard
}()

// 清除UserDefaultsObject(
func removeAllUserDefaultsObject() {
    
    let appDomain = Bundle.main.bundleIdentifier!
    userDefaults.removePersistentDomain(forName: appDomain)
    
    //        userDefaults.set(100.0, forKey: "perfect")
    //        userDefaults.setPersistentDomain(["123":"543"], forName: "aaa")
    //        userDefaults.set("aaaa", forKey: "bbb")
    //        userDefaults.setVolatileDomain(["321":"23123"], forName: "aaa")
    //
    //        print(userDefaults.double(forKey: "perfect"))
    //        print(userDefaults.persistentDomain(forName: "aaa"))
    //        print(userDefaults.object(forKey: "bbb"))
    //        print(userDefaults.volatileDomain(forName: "aaa"))
    //
    //
    //        removeAllUserDefaultsObject()
    //
    //
    //        print(userDefaults.double(forKey: "perfect"))
    //        print(userDefaults.string(forKey: "aaa"))
    //        print(userDefaults.object(forKey: "bbb"))
    //FIXME: - aaaa
    //        为什么不能清除？？？
    //        print(userDefaults.volatileDomain(forName: "aaa"))
}




//MARK: - 资源管理
public enum R {
    //字体
    enum font {
        //微软雅黑
        static func pingFangSC(_ size: CGFloat) ->UIFont? {
            return UIFont.init(name: "PingFangSC-Regular", size: size)
        }
        //粗体
        static func bold(_ size: CGFloat) ->UIFont?{
            UIFont.init(name: "Helvetica-Bold", size: size)
        }
    }
    //常用图片
    enum image {
        static var logo = UIImage.init(named: "XXXXXX")
    }
}

//MARK: - 获取屏幕宽高 & 按照375宽屏幕比例适配
public struct ScreenTool {
    //屏幕宽
    static var screenW = {
        UIScreen.main.bounds.size.width
    }()
    //屏幕高
    static var screenH = {
        UIScreen.main.bounds.size.height
    }()
    //导航栏高
    static var navH = {
        ScreenTool.screenH >= 812 ? 88 : 64
    }()
    //状态栏高
    static var statusH = {
        ScreenTool.screenH >= 812 ? 44 : 20
    }()
    //tabbar高
    static var tabBarH = {
        ScreenTool.screenH >= 812 ? 83 : 49
    }()
    //按照375宽屏幕比例适配
    static func px(_ v: CGFloat) -> CGFloat {
        if ScreenTool.screenW == 375 {
            return v
        }
        return v * ScreenTool.screenW/375
    }
}

//MARK: - 快速颜色生成
public struct ColorTool{
    
    static func RGB(r: CGFloat, g: CGFloat, b: CGFloat, alph: CGFloat = 1) -> UIColor{
        UIColor.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alph)
    }
    
    static func RGB16xFF(rgbValue: Int) -> UIColor{
        
        let red = (CGFloat((rgbValue & 0xFF0000) >> 16))/255.0
        let green = (CGFloat((rgbValue & 0xFF00) >> 8))/255.0
        let blue = (CGFloat((rgbValue & 0xFF)))/255.0
        return UIColor.init(red: red, green: green, blue: blue, alpha: 1)
    }
}

//MARK: - 多线程封装 & 延迟执行
public struct Dispatch {
    
    public typealias Task = () ->Void
    /*
     多线程
     */
    //子线程执行
    public static func dispachAsync(_ task: @escaping Task){
        _dispachAsync(task)
    }
    //子线程任务完成后回到执行主线程执行
    public static func dispachAsync(task: @escaping Task, mainTask: @escaping Task){
        _dispachAsync(task,mainTask)
    }
    
    private  static func _dispachAsync(_ task: @escaping Task, _ mainTask: Task? = nil){
        
        let itme = DispatchWorkItem.init(block: task)
        DispatchQueue.global().async(execute: itme)
        if let main = mainTask {
            itme.notify(queue: DispatchQueue.main, execute: main)
        }
    }
    /*
     延迟执行
     */
    //主线程延迟执行
    @discardableResult
    public static func delay(_ seconds: Double, _ task: @escaping Task) -> DispatchWorkItem {
        
        let item = DispatchWorkItem.init(block: task)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
        return item
    }
    //子线程延迟执行
    @discardableResult
    public static func asyncDelay(_ seconds: Double, _ task: @escaping Task) -> DispatchWorkItem{
        _asyncDilay(seconds, task)
    }
    //子线程任务延迟执行完后执行主线任务
    @discardableResult
    public static func asyncDelay(_ seconds: Double, _ task: @escaping Task, _ mainTask: @escaping Task) -> DispatchWorkItem{
        _asyncDilay(seconds, task, mainTask)
    }
    
    @discardableResult
    private static func _asyncDilay(_ seconds: Double, _ task: @escaping Task, _ mianTask: Task? = nil) -> DispatchWorkItem{
        
        let itme = DispatchWorkItem.init(block: task)
        DispatchQueue.global().asyncAfter(deadline: .now() + seconds, execute: itme)
        if let main = mianTask {
            itme.notify(queue: DispatchQueue.main, execute: main)
        }
        return itme
    }
}

//MARK: - 判断是否为奇数
extension BinaryInteger {
    //是否为奇数
    func isOdd() -> Bool {
        self % 2 != 0
    }
}

//MARK: - 调整按钮image与lable的位置
enum BtnImagePositionType {
    case left   //图片在左，标题在右，默认风格
    case right   //图片在右，标题在左
    case top     //图片在上，标题在下
    case bottom  //图片在下，标题在上
}

extension UIButton{
    
    func setImagePosition(type: BtnImagePositionType, spacing: CGFloat){
        
        let image = self.image(for: UIControl.State.normal)
        let text = self.titleLabel?.text
        

        
        let imageSize: CGSize = (image != nil) ? image!.size : CGSize.zero
        let font = self.titleLabel?.font
        let textSize: CGSize =  (text != nil) ? text!.size(withAttributes: [NSAttributedString.Key.font : font!]) : CGSize.zero
        
        
        switch type {
            
        case BtnImagePositionType.left:
           
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: spacing, bottom: 0, right: 0)
            self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: spacing)
        case BtnImagePositionType.right:
            
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageSize.width, bottom: 0, right: imageSize.width + spacing)
            self.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: textSize.width + spacing, bottom: 0, right: -textSize.width)
        case BtnImagePositionType.top:
            
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0)
            self.imageEdgeInsets = UIEdgeInsets.init(top: -(textSize.height + spacing), left: 0, bottom: 0, right: -textSize.width)
            // 使图文不超出btn的高
            self.contentEdgeInsets = imageSize.height > textSize.height ? UIEdgeInsets.init(top: (textSize.height+spacing)/2, left: 0, bottom: (textSize.height+spacing)/2, right: 0) : UIEdgeInsets.init(top: (imageSize.height+spacing)/2, left: 0, bottom: (imageSize.height+spacing)/2, right: 0);
        case BtnImagePositionType.bottom:
            
            self.titleEdgeInsets = UIEdgeInsets.init(top: -(imageSize.height + spacing), left: -imageSize.width, bottom: 0, right: 0)
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: -(textSize.height + spacing), right: -textSize.width)
            // 使图文不超出btn的高
            self.contentEdgeInsets = imageSize.height > textSize.height ? UIEdgeInsets.init(top: (textSize.height + spacing)/2, left: 0, bottom: (textSize.height+spacing)/2, right: 0) : UIEdgeInsets.init(top: (imageSize.height+spacing)/2, left: 0, bottom: (imageSize.height+spacing)/2, right: 0)
        }
    }
    
}

//MARK: - 路径
public struct PathTool{
    static let homePath:String = {
        NSHomeDirectory()
    }()
    //保存应⽤运行时生成的需要持久化的数据
    static let documentPath:String = {
        NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
    }()
    // 获取Cache目录
    static let cachePath:String = {
        NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
    }()
    // 获取Library目录
    static let libraryPath:String = {
        NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last!
    }();
    // 获取Tmp目录
    static let tempPath = {
        NSTemporaryDirectory()
    }()
}

//MARK: - 打印
func akLog<T>(_ msg: T,
              file: NSString = #file,
              line: Int = #line,
              fn: String = #function){
    #if DEBUG
    let prefix = "\(file.lastPathComponent) -> \(fn) -> \(line)行:"
    print(prefix,msg)
    #endif
}

